package com.xiaoyu.izf.controller.api;

import cn.hutool.core.lang.Validator;
import cn.hutool.core.util.IdUtil;
import cn.hutool.crypto.SecureUtil;
import com.xiaoyu.izf.config.MyConfig;
import com.xiaoyu.izf.config.SysConfig;
import com.xiaoyu.izf.model.AppSendMsgCode;
import com.xiaoyu.izf.model.UserCardInfo;
import com.xiaoyu.izf.model.UserInfo;
import com.xiaoyu.izf.model.exception.BusinessException;
import com.xiaoyu.izf.model.exception.BusinessStatusEnum;
import com.xiaoyu.izf.model.page.FormResult;
import com.xiaoyu.izf.model.page.UserByOSNBean;
import com.xiaoyu.izf.service.AppSendMsgCodeService;
import com.xiaoyu.izf.service.CommissionGetLogService;
import com.xiaoyu.izf.service.UserInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.sql.Timestamp;
import java.util.List;

@RestController
@RequestMapping("/api/user")
public class UserApiController extends BaseApiController {
    @Autowired
    private MyConfig myConfig;
    @Autowired
    private UserInfoService userInfoService;
    @Autowired
    private AppSendMsgCodeService appSendMsgCodeService;
    @Autowired
    private CommissionGetLogService commissionGetLogService;

    @RequestMapping("/reg")
    public FormResult<UserInfo> reg(HttpServletRequest request, String userName, String pwd, String pushCode){
        FormResult<UserInfo> fr = new FormResult<UserInfo>();
        if(!Validator.isMobile(userName)){
            fr.setStatus(500);
            fr.setMessage("手机号码不正确。");
            return fr;
        }
        UserInfo user = userInfoService.findByUserName(userName);
        if(user!=null){
            fr.setStatus(500);
            fr.setMessage("用户已经存在。");
            return fr;
        }
        UserInfo pushUser = null;
        if(!StringUtils.isEmpty(pushCode)){
            pushUser = userInfoService.userInfoByPushCode(pushCode);
            if(pushUser==null){
                fr.setStatus(500);
                fr.setMessage("推广码错误。");
                return fr;
            }
            if(pushUser.getVipType()==0){
                fr.setStatus(500);
                fr.setMessage("无推广资格。");
                return fr;
            }
        }
        //user = userInfoService.userInfoAdd(userName,pwd,pushUser);
        fr.setStatus(200);
        fr.setMessage("ok");
        user.setPwd("");
        user.setHeadImgUrl(myConfig.getHost()+user.getHeadImgUrl());
        fr.setData(user);
        return fr;
    }

    @RequestMapping("/reg2")
    public FormResult reg2(HttpServletRequest request, String userName,String nickName, String pwd, String pushCode, String msgCode){
        FormResult<UserInfo> fr = new FormResult<UserInfo>();
        String cid = request.getHeader("cid");
        if(StringUtils.isEmpty(cid)){
            fr.setStatus(500);
            fr.setMessage("非法访问。");
            return fr;
        }
        if(!Validator.isMobile(userName)){
            fr.setStatus(500);
            fr.setMessage("手机号码不正确。");
            return fr;
        }
        AppSendMsgCode appSendMsgCode = appSendMsgCodeService.getOne(cid);
        if(StringUtils.isEmpty(appSendMsgCode.getMsgCode())||(System.currentTimeMillis()-appSendMsgCode.getSendTime().getTime()>20*60*1000)){
            fr.setStatus(500);
            fr.setMessage("手机验证码已过期。");
            return fr;
        }
        if(!appSendMsgCode.getMsgCode().equals(msgCode)){
            fr.setStatus(500);
            fr.setMessage("手机验证码错误。");
            return fr;
        }
        UserInfo user = userInfoService.findByUserName(userName);
        if(user!=null){
            fr.setStatus(500);
            fr.setMessage("用户已经存在。");
            return fr;
        }
        if(StringUtils.isEmpty(nickName)){
            nickName = "请设置用户名";
        }
        UserInfo pushUser = null;
        /*if(!StringUtils.isEmpty(pushPhone)&&!StringUtils.isEmpty(pushCode)){
            pushUser = userInfoService.userInfoByPushCode(pushCode);
            if(pushUser==null){
                return new FormResult<>(BusinessStatusEnum.ERROR,"推广码错误","推广码错误");
            }
            if(pushUser.getUserName().equals(pushPhone)){
                return new FormResult<>(BusinessStatusEnum.ERROR,"您的推广人手机号与授权码信息不符","您的推广人手机号与授权码信息不符");
            }
            if(pushUser.getVipType()==0){
                return new FormResult<>(BusinessStatusEnum.ERROR,"推广人无推广资格","推广人无推广资格");
            }
        }else if(!StringUtils.isEmpty(pushPhone)){
            pushUser = userInfoService.findByUserName(pushPhone);
            if(pushUser==null){
                fr.setStatus(500);
                fr.setMessage("推广码错误。");
                return fr;
            }
            if(pushUser.getVipType()==0){
                fr.setStatus(500);
                fr.setMessage("推广人无推广资格");
                return fr;
            }
        }*/
        if(!StringUtils.isEmpty(pushCode)){
            if(pushCode.length()==11){
                pushUser = userInfoService.findByUserName(pushCode);
            }else {
                pushUser = userInfoService.userInfoByPushCode(pushCode);
            }
            if(pushUser==null){
                fr.setStatus(500);
                fr.setMessage("推广码错误。");
                return fr;
            }
            if(pushUser.getVipType()==0){
                fr.setStatus(500);
                fr.setMessage("推广人无推广资格");
                return fr;
            }
        }
        user = userInfoService.userInfoAdd(userName,nickName,pwd,pushUser);
        fr.setStatus(200);
        fr.setMessage("ok");
        user.setPwd("");
        user.setHeadImgUrl(myConfig.getHost()+user.getHeadImgUrl());
        fr.setData(user);
        return fr;
    }

    @RequestMapping("/is_exist")
    public FormResult userIsExist(String phone){
        if(!Validator.isMobile(phone)){
            return new FormResult<>(BusinessStatusEnum.ERROR,"手机号码不正确","手机号码不正确");
        }
        UserInfo user = userInfoService.findByUserName(phone);
        if(user!=null){
            return new FormResult<>(200,"exist","exist");
        }else{
            return new FormResult<>(200,"no_exist","no_exist");
        }
    }

    @RequestMapping("/forget_pwd")
    public FormResult forgetPwd(HttpServletRequest request, String userName, String pwd, String msgCode){
        String cid = request.getHeader("cid");
        if(StringUtils.isEmpty(cid)){
            return new FormResult(BusinessStatusEnum.ERROR,"非法访问");
        }
        if(!Validator.isMobile(userName)){
            return new FormResult(BusinessStatusEnum.ERROR,"手机号码不正确");
        }
        AppSendMsgCode appSendMsgCode = appSendMsgCodeService.getOne(cid);
        if(StringUtils.isEmpty(appSendMsgCode.getMsgCode())||(System.currentTimeMillis()-appSendMsgCode.getSendTime().getTime()>20*60*1000)){
            return new FormResult(BusinessStatusEnum.ERROR,"手机验证码已过期");
        }
        if(!appSendMsgCode.getMsgCode().equals(msgCode)){
            return new FormResult(BusinessStatusEnum.ERROR,"手机验证码错误");
        }
        UserInfo user = userInfoService.findByUserName(userName);
        if(user==null){
            return new FormResult(BusinessStatusEnum.ERROR,"用户不存在");
        }
        pwd = SecureUtil.md5(pwd+ SysConfig.pwdEx);
        user.setPwd(pwd);
        userInfoService.userSave(user);
        user.setPwd("");
        return new FormResult(BusinessStatusEnum.OK,user);
    }

    @RequestMapping("/login")
    public FormResult<UserInfo> login(HttpServletRequest request, String userName, String pwd){
        FormResult<UserInfo> fr = new FormResult<UserInfo>();
        String pwd2 = SecureUtil.md5(pwd+ SysConfig.pwdEx);
        UserInfo user = userInfoService.findByUserName(userName);
        if(user==null){
            fr.setStatus(404);
            fr.setMessage("用户名或密码不正确。");
            return fr;
        }
        if(!user.getPwd().equals(pwd2)){
            fr.setStatus(500);
            fr.setMessage("用户名或密码不正确。");
            return fr;
        }
        if(user.getIsAdmin()==1){
            fr.setStatus(500);
            fr.setMessage("Admin用户不能登录。");
            return fr;
        }
        String token = IdUtil.simpleUUID();
        user.setToken(token);
        user.setLastLoginTime(new Timestamp(System.currentTimeMillis()));
        userInfoService.userSave(user);
        user.setPwd("");
        user.setHeadImgUrl(myConfig.getHost()+user.getHeadImgUrl());
        fr.setStatus(200);
        fr.setMessage("ok");
        fr.setData(user);
        return fr;
    }

    @RequestMapping("/info")
    public FormResult<UserInfo> userInfo(HttpServletRequest request){
        FormResult<UserInfo> fr = new FormResult<>();
        UserInfo user = getUserByToken(request);
        //UserInfo user = userInfoService.userInfo(uid);
        fr.setStatus(200);
        fr.setMessage("ok");
        user.setPwd("");
        user.setOfficialServiceNumber(user.getOfficialServiceNumberView());

        //System.out.println(myConfig.getHost());
        user.setHeadImgUrl(myConfig.getHost()+user.getHeadImgUrl());
        //System.out.println(user);
        fr.setData(user);
        return fr;
    }

    /**
     * 用户获取绑定的银行卡信息
     * @return
     */
    @RequestMapping("/card")
    @ResponseBody
    public FormResult<UserCardInfo> userCardOne(HttpServletRequest request){
        FormResult<UserCardInfo> fr = new FormResult<>();
        UserInfo user = getUserByToken(request);
        UserCardInfo card = userInfoService.userCardOne(user.getId());
        fr.setStatus(200);
        fr.setMessage("ok");
        fr.setData(card);
        return fr;
    }

    /**
     * 用户银行卡绑定
     * @return
     */
    @RequestMapping("/card_save")
    @ResponseBody
    public FormResult<UserCardInfo> userCardAdd(HttpServletRequest request, String userName, String account, String bankName, String bankBranchName){
        System.out.println(userName+"=="+account);
        FormResult<UserCardInfo> fr = new FormResult<UserCardInfo>();
        UserInfo user = getUserByToken(request);
        UserCardInfo card = userInfoService.userCardAdd(user.getId(),userName,account,bankName,bankBranchName);
        fr.setStatus(200);
        fr.setMessage("ok");
        fr.setData(card);
        return fr;
    }

    /**
     * 修改昵称
     * @param request
     * @param newNick
     * @return
     */
    @PostMapping("/nick/update")
    public FormResult nickNameUpdate(HttpServletRequest request, String newNick){
        if (newNick==null||newNick.length()>25||newNick.length()<2){
            throw new BusinessException(BusinessStatusEnum.ERROR,"参数未传递或长度不正确");
        }
        UserInfo userInfo = getUserByToken(request);
        userInfo.setNickName(newNick);
        userInfoService.userSave(userInfo);
        return new FormResult(BusinessStatusEnum.OK);
    }

    /**
     * 修改头像
     * @param request
     * @param headUrl
     * @return
     */
    @PostMapping("/head/update")
    public FormResult headUpdate(HttpServletRequest request, String headUrl){
        UserInfo userInfo = getUserByToken(request);
        userInfo.setHeadImgUrl(headUrl);
        userInfoService.userSave(userInfo);
        return new FormResult(BusinessStatusEnum.OK);
    }

    /**
     * 申请提现
     * @param request
     * @param moneyApply 申请金额
     * @return
     */
    @PostMapping("/withdraw/apply")
    public FormResult withdrawApply(HttpServletRequest request, String moneyApply){
        UserInfo user = getUserByToken(request);
        UserCardInfo card = userInfoService.userCardOne(user.getId());
        if(card==null||"".equals(card.getBankAccount())){
            return new FormResult(BusinessStatusEnum.ERROR,"","请先绑定银行卡");
        }
        int amount = 0;
        try {
            double d = Double.parseDouble(moneyApply);
            amount = (int)(d*100);
        }catch (Exception e){
            return new FormResult(BusinessStatusEnum.ERROR,"","金额不正确");
        }
        userInfoService.applyWithdraw(user,amount);

        return new FormResult(BusinessStatusEnum.OK);
    }

    /**
     * 提现列表
     * @param request
     * @return
     */
    @RequestMapping("/withdraw/list")
    public FormResult withdrawList(HttpServletRequest request, int p, int psize){
        UserInfo user = getUserByToken(request);
        return new FormResult(BusinessStatusEnum.OK,commissionGetLogService.withdrawList(user,p,psize));
    }

    @PostMapping("/pwd/forgotten")
    public FormResult forgetPwd(){

        return null;
    }

    @RequestMapping("/get_grade_push_user")
    public FormResult getPushUser(HttpServletRequest request){
        UserInfo user = getUserByToken(request);
        //UserInfo user = userInfoService.userInfo(uid);
        if(user.getPushUid()>0) {
            UserInfo userInfo = userInfoService.userInfo(user.getPushUid());
            userInfo.setPwd("");
            userInfo.setToken("");
            userInfo.setHeadImgUrl(myConfig.getHost()+userInfo.getHeadImgUrl());
            return  new FormResult(BusinessStatusEnum.OK,userInfo);
        } else {
            throw new BusinessException(BusinessStatusEnum.NOT_EXIST,"没有推荐人");
        }
    }

    @RequestMapping("/push_list")
    public FormResult pushUserList(HttpServletRequest request){
        UserInfo user = getUserByToken(request);
        List<UserInfo> list = userInfoService.pushUserList(user.getId());
        if(list!=null&&list.size()>0){
            list.forEach(item->{
                item.setPwd("");
                item.setToken("");
                item.setHeadImgUrl(myConfig.getHost()+item.getHeadImgUrl());
            });
            return new FormResult(BusinessStatusEnum.OK,list);
        }
        throw new BusinessException(BusinessStatusEnum.NOT_EXIST,"没有查询到数据");
    }

    @RequestMapping("/commission/list")
    public FormResult commissionLogList(HttpServletRequest request, int p, int psize){
        UserInfo user = getUserByToken(request);
        return new FormResult(BusinessStatusEnum.OK,commissionGetLogService.commissionLogs(user.getId(),p,psize));
    }

    @RequestMapping("/query_osn")
    @CrossOrigin(origins = "*")
    public FormResult queryByOfficialServiceNumber(HttpServletRequest request,String osn){
        if(StringUtils.isEmpty(osn)||osn.length()<14){
            return new FormResult(BusinessStatusEnum.ERROR,"","服务号错误");
        }
        osn = osn.substring(5);
        UserInfo user = userInfoService.findByOSN(osn);
        if(user!=null&&user.getVipType()>0){
            UserByOSNBean bean = new UserByOSNBean();
            bean.setPhone(user.getUserName());
            bean.setNickName(user.getNickName());
            bean.setVipTypeName(user.getVipTypeName());
            return new FormResult(BusinessStatusEnum.OK,bean);
        }
        return new FormResult(BusinessStatusEnum.NOT_EXIST,"","数据不存在");
    }

}
